package com.hx.mypetstore.ui.Login;

import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.AppCompatEditText;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.hx.mypetstore.Bean.UserBean;
import com.hx.mypetstore.R;
import com.hx.mypetstore.constant.SPConstants;
import com.hx.mypetstore.network.HttpURL;
import com.hx.mypetstore.util.SPUtil;
import com.hx.mypetstore.util.ToastUtil;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.List;
import java.util.Objects;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class RegisterActivity extends AppCompatActivity {
    // 手机号
    private AppCompatEditText mEtPhoneName;
    // 密码
    private AppCompatEditText mEtPassword;
    // 密码Check
    private AppCompatEditText mEtPasswordDouble;
    private String TAG = "注册";
    // 本地用户数据
    private List<UserBean> mLocalData;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_SECURE, WindowManager.LayoutParams.FLAG_SECURE);
        // 初始化View
        initView();
        // 初始化数据
        initData();
    }

    /**
     * 初始化View
     */
    private void initView() {
        // 顶部返回
        ImageView mIvBack = findViewById(R.id.title_back);
        // 用户名
        mEtPhoneName = findViewById(R.id.register_username);
        // 密码
        mEtPassword = findViewById(R.id.register_password);
        // 密码Check
        mEtPasswordDouble = findViewById(R.id.register_password_double);

        mIvBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 返回
                finish();
            }
        });

        findViewById(R.id.register_register).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 注册
                onRegister();
            }
        });

    }

    /**
     * 初始化数据
     */
    private void initData() {
        String localStr = (String) SPUtil.get(this, SPConstants.KEY_LOCAL_USER, "");
        if (TextUtils.isEmpty(localStr)) {
            mLocalData = null;
            return;
        }
        try {
            Gson gson = new Gson();
            mLocalData = gson.fromJson(localStr, new TypeToken<List<UserBean>>() {
            }.getType());
        } catch (Exception ignored) {

        }
    }

    /**
     * 登录
     */
    private void onRegister() {
        String name = Objects.requireNonNull(mEtPhoneName.getText()).toString().trim();

        String password = mEtPassword.getText().toString().trim();
        String passwordDouble = mEtPasswordDouble.getText().toString().trim();

        //判断账户是否为空
        if(TextUtils.isEmpty(name))
        {
            ToastUtil.getInstance().showShort(this,R.string.toast_inputname);
        }
        //判断密码是否为空
        if (TextUtils.isEmpty(passwordDouble)) {
            ToastUtil.getInstance().showShort(this, R.string.toast_input_password_double);
            return;
        }
        if (TextUtils.isEmpty(password)) {
            ToastUtil.getInstance().showShort(this, R.string.toast_input_password);
            return;
        }
        //判断密码是否相等
        if (!password.equals(passwordDouble)) {
            ToastUtil.getInstance().showShort(this, R.string.toast_passwords_different);
            return;
        }

        String url = HttpURL.REGISTER;
        //发送注册请求
        OkHttpClient okHttpClient = new OkHttpClient();
        RequestBody requestBody = new FormBody.Builder()
                .add("phone", name)
                .add("password",password)
                .build();
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.d(TAG, "onFailure: " + e.getMessage());
            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                try {
                    JSONObject jsonObject = new JSONObject(response.body().string());
                    Log.e(TAG, jsonObject.toString() );
//                    if (!jsonObject.getBoolean("success")) {
//                        Toast toast = Toast.makeText(getApplication(), jsonObject.getString("message"), Toast.LENGTH_SHORT);
//                        toast.show();
//                    }else {
//                        Gson gson = new Gson();
//                        UserBean user = gson.fromJson(jsonObject.getString("data"), UserBean.class);
//                        SPUtil.put(getApplication(), SPConstants.KEY_LOGIN, true);
//                        SPUtil.put(getApplication(), SPConstants.KEY_HW_LOGIN, false);
//                        SPUtil.put(getApplication(), SPConstants.KEY_NICK_NAME, user.getUsername());
//                        startActivity(new Intent(getApplication(), MainActivity.class));
//                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
        // 保存用户信息
//        UserBean userBean = new UserBean(name, password, UUIDUtil.getUUID());
//        if (mLocalData == null || mLocalData.size() == 0) {
//            mLocalData = new ArrayList<>();
//        }
//        mLocalData.add(userBean);
//        Gson gson = new Gson();
//        String localStr = gson.toJson(mLocalData);
//
//        SPUtil.put(this, SPConstants.KEY_LOGIN, true);
//        SPUtil.put(this, SPConstants.KEY_NICK_NAME, name);
//        SPUtil.put(this, SPConstants.KEY_LOCAL_USER, localStr);
        finish();
    }

}